<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="计划类型">
      <el-select v-model="form.type" placeholder="请选择计划类型" @change="form.name=form.type">
        <el-option label="普通会员" value="普通会员" />
        <el-option label="超级会员" value="超级会员" />
        <el-option label="super会员" value="super会员" />
      </el-select>
    </el-form-item>
    <el-form-item label="计划名称">
      <el-input v-model="form.name"/>
    </el-form-item>
    <el-form-item label="计划金额">
      <el-input v-model="form.price"/>
    </el-form-item>
    <el-form-item label="计划时间">
      <el-input v-model="form.time"/>
    </el-form-item>
    <el-form-item label="计划状态">
      <el-select v-model="form.status" placeholder="请选择计划状态">
        <el-option label="启用" value="online" />
        <el-option label="禁用" value="offline" />
        <el-option label="隐藏" value="hide" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">确认提交</el-button>
      <el-button @click="emit('close-dialog')">取消</el-button>
    </el-form-item>

  </el-form>
</template>

<script lang="ts" setup>
import {reactive, onMounted} from 'vue'
import {ElLoading, ElMessage} from 'element-plus'
import { defineEmits } from 'vue';
import router from "@/router";

const emit = defineEmits(['close-dialog'])

const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return loading;
};

// 表单的响应式数据
const form = reactive({
  ID:'',
  RID:'',
  type:'',
  name: '',
  price:'',
  time:0,
  status: '',
})

// 上传相关的数据和方法
const rankPlan_addUrl = 'https://movie.cpb2013.top/admin/rank.php?mode=add_plan' // 替换为你的上传地址

const closeFullScreen = (loading) => {
  loading.close();
};
// 表单提交处理函数
const onSubmit = async () => {
  console.log('提交表单:', form)
  let loading = openFullScreen();
  const formData = new FormData()
  // 遍历并添加到 FormData
  Object.keys(form).forEach((key) => {
    // 排除那些不是字符串或数字的键（例如布尔值或对象）
    // 因为 FormData 主要用于处理键值对形式的字符串数据
    if (typeof form[key] === 'string' || typeof form[key] === 'number') {
      formData.append(key, form[key]);
    } else if (typeof form[key] === 'boolean') {
      // 对于布尔值，你可以决定如何转换为字符串（例如，使用 'true' 或 'false'）
      formData.append(key, form[key] ? '女' : '男');
    }
  });
  formData.delete('ID');
  formData.set('RID', formData.get('type')=='普通会员' ? '1' : formData.get('type')=='超级会员' ? '2' : '3');
  formData.append('key', localStorage.getItem('key'));

  try {
    const response = await fetch(rankPlan_addUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] ==='success')
      {
        ElMessage.success('添加成功！')
        clearForm();
        // emit('close-dialog')
        // this.$emit('close-dialog');
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
      else
      {
        ElMessage.error(result['msg'])
      }
    } else {
      ElMessage.error('添加失败！')
    }
  } catch (error) {
    ElMessage.error('添加失败！')
  }
  closeFullScreen(loading)
}

onMounted(() => {
  // const MID = '06a718d656fac9f771507e1872adc838'; // replace with actual MID
  /*fetchMovieData(props.MID);/!**!/*/
});

function clearForm() {
  for (const key in form) {
    if (form.hasOwnProperty(key)) {
      // Set each property to its initial value
      switch (typeof form[key]) {
        case 'string':
          form[key] = '';
          break;
        case 'number':
          form[key] = 0;
          break;
        case 'boolean':
          form[key] = false;
          break;
        default:
          form[key] = '';
      }
    }
  }
}

/*watch(() => props.MID, (newMID) => {
  fetchMovieData(newMID);
});*/

</script>
